package com.github.lee.unsplash.ui.topic

import androidx.hilt.lifecycle.ViewModelInject
import com.github.lee.core.common.LogUtil
import com.github.lee.mvvm.core.vm.BaseRefreshViewModel
import com.github.lee.unsplash.domain.TopicBean
import com.github.lee.unsplash.model.repository.TopicRepository

class TopicVM @ViewModelInject constructor(private val rep: TopicRepository) :
    BaseRefreshViewModel<TopicBean, HomeTopicAdapter>() {

    override fun onCreateAdapter(): HomeTopicAdapter = HomeTopicAdapter()

    fun refreshOrLodeMore(isRefresh: Boolean) {
        if (isRefresh) {
            currentPage = 1
        } else {
            currentPage++
        }
        requestForResult({
            rep.topics(currentPage, 10)
        }, {
            if (!it.isSuccess()) {
                if (isRefresh && data.isNullOrEmpty()) {
                    postError(-1, it.msg)
                } else {
                    postToast(it.msg)
                }
                return@requestForResult
            }
            val list = it.data
            if (list.isNullOrEmpty()) {
                if (isRefresh && data.isNullOrEmpty()) {
                    postEmpty(-1, it.msg)
                } else {
                    loadMoreEnd()
                }
                return@requestForResult
            }

            if (isRefresh) {
                setNewData(list)
                stopRefresh()
            } else {
                addData(list)
                if (it.hasMore(currentPage)) {
                    loadMoreComplete()
                } else {
                    loadMoreEnd()
                }
            }
            postSuccess()
        })
    }
}